﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Data.SqlClient;
using System.Web.Configuration;
using Mocola.Common;
using Mocola.Security;
using Mocola.BLL;

namespace Mocola.Net.Web.ajax
{
    public partial class AuthLogon : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string UserNameString = string.Empty;
            if (!string.IsNullOrEmpty(Request.Form["uname"])) UserNameString = Request.Form["uname"].ToString();
            string UserPasswordString = string.Empty;
            if (!string.IsNullOrEmpty(Request.Form["upwd"])) UserPasswordString = Request.Form["upwd"].ToString();

            if (UserNameString.Trim() == string.Empty)
            {
                Response.Write("Fail:请填写用户名!");
                return;
            }
            else if (UserPasswordString.Trim() == string.Empty)
            {
                Response.Write("Fail:请输入密码!");
                return;
            }

            ConnectionStringSettings connString = WebConfigurationManager.ConnectionStrings["MocolaNet"];
            SqlConnection connection1 = new SqlConnection(connString.ConnectionString);
            SqlCommand command1 = connection1.CreateCommand();
            command1.CommandText = "SELECT UserID, UserName, UserPwd, Status FROM Moc_Users WHERE UserName=@UserName";
            command1.Parameters.Add("@UserName", SqlDbType.NVarChar);
            command1.Parameters["@UserName"].Value = UserNameString.Trim();
            connection1.Open();
            SqlDataReader reader1 = command1.ExecuteReader(CommandBehavior.CloseConnection);

            try
            {
                while (reader1.Read())
                {
                    int UserIDInt = reader1.GetInt32(0);
                    string NameString = reader1.GetString(1);
                    string PasswordString = reader1.GetString(2);
                    int StatusInt = reader1.GetInt32(3);

                    if (StatusInt != 1)
                    {
                        MD5Verifier md5 = new MD5Verifier();

                        if (md5.verifyMd5Hash(UserPasswordString.Trim(), PasswordString))
                        {
                            Response.Write(SetUserDataAndRedirect(NameString, UserIDInt.ToString()));
                            return;
                        }
                    }
                    else
                    {
                        Response.Write("Fail:该用户被锁定!");
                    }
                }

                Response.Write("Fail:登陆失败!");
            }
            finally
            {
                reader1.Close();
            }
        }

        private string SetUserDataAndRedirect(string userName, string userData)
        {
            // 获得Cookie
            HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userName, true);

            // 得到ticket凭据
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

            // 根据之前的ticket凭据创建新ticket凭据，然后加入自定义信息
            FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(
                ticket.Version, ticket.Name, ticket.IssueDate,
                ticket.Expiration, ticket.IsPersistent, userData);

            // 将新的Ticke转变为Cookie值，然后添加到Cookies集合中
            authCookie.Value = FormsAuthentication.Encrypt(newTicket);
            HttpContext.Current.Response.Cookies.Add(authCookie);

            // 获得 来到登录页之前的页面，即url中return参数的值
            string url = FormsAuthentication.GetRedirectUrl(userName, true);

            return url;
        }
    }
}
